package com.producer.producer;

import com.producer.model.RocketMqGroupTopic;
import com.producer.utils.BeanUtil;
import com.producer.utils.DateUtil;
import com.producer.model.Message;
import com.producer.model.table.SysMessage;
import com.producer.utils.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.producer.utils.SendMsgUtil;
import com.producer.service.MessageService;
import com.producer.service.impl.MessageServiceImpl;

import javax.servlet.http.HttpServletRequest;

/**
 * MQ生产者
 * 向消息服务器发送消息
 *
 * @author Liunh
 */
@Slf4j
@Component
public class DemoMqProducer {

    private final MessageService messageService;
    private final SendMsgUtil rocketMqUtil;

    public DemoMqProducer(MessageServiceImpl messageService, SendMsgUtil rocketMqUtil) {
        this.messageService = messageService;
        this.rocketMqUtil = rocketMqUtil;
    }

    public boolean send(Message<String> msg, HttpServletRequest request) throws Exception {
        log.info(">>>>>> 将接收的XXX数据发送到消息队列:{}", msg == null ? null : JacksonUtil.beanToJson(msg));
        boolean result = Boolean.TRUE;
        if (msg != null) {
            String batchNo = String.valueOf(System.currentTimeMillis());
            if (StringUtils.isNotBlank(msg.getBatchNo())) {
                batchNo = msg.getBatchNo();
            }
            final SysMessage sysMessage = new SysMessage();
            BeanUtil.copyPropertiesExcludeNullAndEmpty(msg, sysMessage);
            sysMessage.setBatchNo(batchNo);
            sysMessage.setCreateTime(DateUtil.getCurrentDate());
            if (msg.getSendTime().after(DateUtil.getCurrentDate())) {
                sysMessage.setStatus(0);
                messageService.add(sysMessage);
            } else {
                sysMessage.setStatus(1);
                try {
                    rocketMqUtil.sendMsg(JacksonUtil.beanToJson(sysMessage), RocketMqGroupTopic.Topic.TEST_TOPIC, RocketMqGroupTopic.Tag.TEST_TAG);
                } catch (Exception e) {
                    log.error(">>>>>> 将接收的XXX数据发送到消息队列，batchNo：{}", batchNo, e);
                    result = Boolean.FALSE;
                }
            }
        }
        return result;
    }

}
